package com.slg.android.listenbook.biz.home.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.listenbook.R;
import com.slg.android.listenbook.biz.home.MainActivity;
import com.slg.android.listenbook.biz.home.adapter.ChannelAdapter;
import com.slg.android.listenbook.biz.home.moudle.Channel;
import com.slg.android.listenbook.common.DataStore;
import com.slg.android.listenbook.common.FragmentMessageListener;
import com.slg.android.listenbook.configuration.Constants;
import com.slg.android.listenbook.configuration.app.MainConstants;
import com.slg.android.listenbook.net.http.HttpClientProxy;
import com.slg.android.listenbook.net.http.JsonCallBack;

import java.util.ArrayList;
import java.util.List;

import dev.dworks.libs.astickyheader.SimpleSectionedListAdapter;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChannelFragment extends Fragment implements AdapterView.OnItemClickListener
        , JsonCallBack,MainConstants {
    @ViewInject(R.id.channel_list)
    private ListView mListView;
    private List<Channel> mData;
    private ArrayList<SimpleSectionedListAdapter.Section> mSections;
    private ChannelAdapter mAdapter;
    private String[] mChannelId;
    private final int GET_MUSIC_LIST = 1;
    private FragmentMessageListener mListener;


    public ChannelFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Activity activity) {
        if(activity instanceof FragmentMessageListener){
            mListener = (FragmentMessageListener) activity;
        }
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_channel, container, false);
        ViewUtils.inject(this, view);
        mAdapter = new ChannelAdapter(mData, getActivity());
        SimpleSectionedListAdapter simpleSectionedListAdapter =
                new SimpleSectionedListAdapter(getActivity()
                        , mAdapter, R.layout.item_channel_header, R.id.header);
        simpleSectionedListAdapter.setSections(mSections.toArray(new SimpleSectionedListAdapter.Section[0]));
        mListView.setAdapter(simpleSectionedListAdapter);
        mListView.setOnItemClickListener(this);

        return view;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mSections = new ArrayList<>();
        mData = new ArrayList<>();
        List<Channel> list = DataStore.getInstance().getChannelList();
        ArrayList<String> cates = new ArrayList<String>();
        for (Channel channel : list) {
            String cate = channel.getCate();
            if (!cates.contains(cate)) {
                cates.add(cate);
            }
        }
        mChannelId = new String[cates.size() + list.size()];
        //Log.d("data", Arrays.toString(list.toArray()));
        int index = 0;
        int idIndex = 0;
        for (String cate : cates) {
            int count = 0;
            mChannelId[idIndex++] = "cate";
            for (Channel channel : list) {
                if (TextUtils.equals(cate, channel.getCate())) {
                    mData.add(channel);
                    count++;
                    index++;
                    mChannelId[idIndex++] = channel.getChannelId();
                }
            }
            SimpleSectionedListAdapter.Section section;
            section = new SimpleSectionedListAdapter.Section(index - count, cate);
            mSections.add(section);
        }
        //Log.d("mSections", Arrays.toString(mSections.toArray()));

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Channel channel = null;
        for (Channel c : mData) {
            if (c.isSelected()) {
                c.setSelected(false);
            }
            if (TextUtils.equals(c.getChannelId(), mChannelId[position])) {
                channel = c;
                channel.setSelected(true);
            }
        }

        SimpleSectionedListAdapter adapter = (SimpleSectionedListAdapter) mListView.getAdapter();
        adapter.notifyDataSetChanged();
        //开启网络下载歌曲列表
        //FM列表 参数1 &_=｛当前时间毫秒数｝参数2&id={channel_id}
        HttpClientProxy proxy = new HttpClientProxy(Constants.FM_LIST);
        String[][] params =
                {
                        {"_", String.valueOf(System.currentTimeMillis())}
                        , {"id", channel.getChannelId()}
                };
        proxy.doGet(params, this, GET_MUSIC_LIST);
    }

    //-------------网络请求回调----------------------
    @Override
    public void onSuccess(ResponseInfo<String> responseInfo, int requestCode) {
        if(requestCode == GET_MUSIC_LIST){
           // Log.d("Channel","success");
            if(mListener != null){
                Intent intent = new Intent();
                intent.putExtra(FRAGMENT_ID,CHANNEL_ID);
                intent.putExtra(DATA_JSON,responseInfo.result);
                mListener.getMessage(intent);
            }

        }
    }

    @Override
    public void onFailure(HttpException error, String msg, int requestCode) {
        switch (requestCode) {
            case GET_MUSIC_LIST:
                Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onStart(int requestCode) {

    }

    @Override
    public void onCancelled(int requestCode) {

    }

    @Override
    public void onLoading(long total, long current, boolean isUploading, int requestCode) {

    }
}
